// #App结构 - 图形编辑器 [editor]
import { App, Frame, Rect, Line, MoveEvent, UI, Bounds, Box, WatchEvent, RenderEvent } from "leafer-ui";
import "@leafer-in/editor"; // 导入图形编辑器插件
// import "@leafer-in/viewport"; // 导入视口插件(可选)
import { Arrow } from "@leafer-in/arrow";
import { ref } from "vue";
import { SheapTypeEnum } from "./enum";

const shapes = [];
function createArrow(x, y) {
  return Arrow.one(
    {
      height: 30,
      startArrow: "arrow",
      endArrow: "none",
      strokeWidth: 3,
      stroke: "red",
      editable: true,
      width: 0,
      rotation: 225,
    },
    x,
    y
  );
}

function createRect(x, y) {
  return Rect.one(
    {
      editable: true,
      strokeWidth: 1,
      stroke: "red",
      closed: true,
      width: 0,
      height: 0,
    },
    x,
    y
  );
}

function checkIntersection(e) {
  const { x, y } = e;
  const point = { x, y };
  return shapes.some((shape) => {
    const { x, y, width, height } = shape.worldBoxBounds;
    const bounds = new Bounds(x - 10, y - height, width + 10, height * 2);
    return bounds.hitPoint(point);
  });
}

function removeWidthShortShape(app, shape, width) {
  const L = 10;
  const bol = width < L;
  if (bol) {
    app.tree.remove(shape);
    shapes.splice(shapes.indexOf(shape), 1);
  }

  return bol;
}

function useLeaferCanvas(currentShapeType, onchange) {
  let app;

  const editing = ref(false);
  const base64 = ref("");
  function createCanvas(cropper, imgWrapRef) {
    if (cropper) {
      editing.value = true;
      const canvas = document.createElement("canvas");
      const { top, left, height, width } = cropper.getCropBoxData();
      imgWrapRef?.value?.appendChild(canvas);
      canvas.width = width;
      canvas.height = height;
      canvas.style.position = "absolute";
      canvas.style.top = top + "px";
      canvas.style.left = left + "px";
      canvas.style.zIndex = 1000;

      app = new App({
        view: canvas,
        width,
        height,
        type: "move",
        editor: { buttonsFixed: true, strokeWidth: 0, pointSize: 0 }, //  配置 editor 会自动创建并添加 app.editor 实例、tree 层、sky 层
      });
      const button = Box.one({
        around: "center",
        fill: "#FEB027",
        width: 20,
        height: 20,
        cornerRadius: 10,
        cursor: "pointer",
        children: [
          {
            tag: "Text",
            fill: "white",
            text: "X",
            fontSize: 14,
            width: 20,
            height: 20,
            textAlign: "center",
            verticalAlign: "center",
          },
        ],
        event: {
          click: () => {
            app.editor.list.forEach((rect) => {
              rect.remove();
              shapes.splice(shapes.indexOf(rect), 1);
            });
            app.editor.target = null;
          },
        },
      });
      app.editor.buttons.add(button);

      let shape;
      let startPoint;
      app.on(MoveEvent.DOWN, (e) => {
        if (app.editor.editing) {
          return;
        }
        // 检测是否与现有的图形相交
        if (checkIntersection(e)) {
          return;
        }
        const { x, y } = e;
        startPoint = { x, y };
        console.log("currentShapeType:", currentShapeType.value);
        switch (currentShapeType.value) {
          case SheapTypeEnum.rect.value:
            shape = createRect(x, y);
            break;
          case SheapTypeEnum.arrow.value:
            shape = createArrow(x, y);
            break;
          default:
            return;
        }

        shapes.push(shape);
        app.tree.add(shape);
      });

      app.on(MoveEvent.DRAG, (e) => {
        if (!shape) return;
        const { x, y } = startPoint;
        const w = Math.abs(e.x - x);
        const h = Math.abs(e.y - y);
        if (currentShapeType.value === SheapTypeEnum.arrow.value) {
          // 计算斜边长度
          const length = Math.hypot(w, h);
          // 计算角度（弧度）并转换为度数
          const angle = Math.atan2(e.y - y, e.x - x) * (180 / Math.PI);
          shape.width = length;
          shape.rotation = angle;
        }

        if (currentShapeType.value === SheapTypeEnum.rect.value) {
          shape.width = e.x - x;
          shape.height = e.y - y;
        }
      });

      app.on(MoveEvent.UP, (e) => {
        console.log("事件触发 pointerup");
        if (!shape) return;
        const { x, y } = startPoint;
        const w = Math.abs(e.x - x);
        const h = Math.abs(e.y - y);
        let length = 0;
        if (shape && currentShapeType.value === SheapTypeEnum.arrow.value) {
          // 计算斜边长度
          length = Math.hypot(w, h);
          removeWidthShortShape(app, shape, length);
        }

        if (shape && currentShapeType.value === SheapTypeEnum.rect.value) {
          // 计算斜边长度
          length = w;
        }
        removeWidthShortShape(app, shape, length);
        shape = null;
        startPoint = null;
      });

      app.on(RenderEvent.RENDER, () => {
        exportBase64();
      });
    }
  }

  function clear() {
    if (app) {
      app.tree.removeAll();
      app.destroy();
      app = null;
    }
    shapes.length = 0;
    onchange("");
    editing.value = false;
  }

  function exportBase64() {
    if (!app) return;
    setTimeout(() => {
      const view = app.view;
      const data = view.toDataURL("image/png", 0.5);
      base64.value = data;
      if (onchange) {
        onchange(data);
      }
    }, 0);
  }

  return {
    createCanvas,
    clear,
    editing,
  };
}

export default useLeaferCanvas;
